#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
int count=1;
pthread_mutex_t lock;
pthread_cond_t condA;
pthread_cond_t condB;
void* startA(void* arg){
  pthread_detach(pthread_self());
  while(1){
    pthread_mutex_lock(&lock);
    if(count<=0){
      pthread_cond_wait(&condA,&lock);
    }
   count--;
    printf("i am threadA\n");
    pthread_mutex_unlock(&lock);
  pthread_cond_signal(&condB);
  }

}
void* startB(void* arg){
  pthread_detach(pthread_self());
  while(1){
    pthread_mutex_lock(&lock);
    if(count>0){
      pthread_cond_wait(&condB,&lock);
    }
    count++;
    printf("i am threadB\n");
    pthread_mutex_unlock(&lock);
  pthread_cond_signal(&condA);  
  }
}
int main() {
  pthread_mutex_init(&lock,NULL);
  pthread_cond_init(&condA, NULL);
  pthread_cond_init(&condB, NULL);
  pthread_t tidA, tidB;
    int ret = pthread_create(&tidA, NULL, startA, NULL);
    if (ret < 0) {
      perror("pthread_create");
      return 0;
    }
    ret = pthread_create(&tidB, NULL, startB, NULL);
    if (ret < 0) {
      perror("pthread_create");
      return 0;
    }

while(1){
  sleep(1);
} 
  pthread_mutex_destroy(&lock);
  pthread_cond_destroy(&condA);
  pthread_cond_destroy(&condB);
  return 0;
}


